package com.knowledge.plus.java8;

import com.knowledge.plus.java8.pojo.Java8Message;
import org.junit.Test;

import java.util.Comparator;
import java.util.List;

/**
 * 集合排序
 *
 * @author TPF
 * @since 2022/11/18
 */
public class CollectSort {

    /**
     * 单个字段排序
     */
    @Test
    public void sortList() {
        List<Java8Message> list = Java8Message.getMessageList();
        {
            System.out.println("===排序前如下===");
            list.forEach(System.out::println);

            // 根据Id升序排序
            list.sort((a, b) -> a.getId().compareTo(b.getId()));
            list.sort(Comparator.comparing(Java8Message::getId));  // 简写

            // 根据Id降序排序(简写)
            list.sort(Comparator.comparing(Java8Message::getId).reversed());

            System.out.println("===排序后如下===");
            list.forEach(System.out::println);
        }
    }

    /**
     * 多个字段组合排序
     */
    @Test
    public void multiAttributeSortList() {
        List<Java8Message> list = Java8Message.getMessageList();
        {
            System.out.println("===排序前如下===");
            list.forEach(System.out::println);

            // 根据多条件组合排序,先根据msg(升序),再根据id(升序)
            list.sort(Comparator.comparing(Java8Message::getMsg).thenComparing(Java8Message::getId));

            // 根据多条件组合排序,先根据msg(升序),再根据id(降序)
            list.sort(Comparator.comparing(Java8Message::getMsg).thenComparing(Comparator.comparing(Java8Message::getId).reversed()));

            // 根据多条件组合排序,先根据msg(降序),再根据id(降序)
            list.sort(Comparator.comparing(Java8Message::getMsg).thenComparing(Java8Message::getId).reversed());

            // 根据多条件组合排序,先根据msg(降序),再根据id(升序)
            list.sort(Comparator.comparing(Java8Message::getMsg).reversed().thenComparing(Java8Message::getId));

            System.out.println("===排序后如下===");
            list.forEach(System.out::println);
        }
    }


}
